/*
 * Copyright (C) 2012 Caldia Apps.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.caldia.android.frameworkG1.sound;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

/**
 * 効果音管理
 * 
 * @author k-matsuda@caldia.org
 * 
 */
public class SoundEffectManager {

	/**
	 * サウンドプール
	 */
	private SoundPool mSoundPool;

	/**
	 * 登録済みのサウンドマップ
	 */
	private final HashMap<Integer, Integer> mSoundMap = new HashMap<Integer, Integer>();

	/**
	 * コンストラクタ
	 */
	public SoundEffectManager() {

	}

	/**
	 * サウンドを読み込む（過去に呼んだものは解放される）
	 * 
	 * @param context
	 *            コンテキスト
	 * @param soundIds
	 *            リソースID配列
	 */
	public void load(final Context context, final int[] soundIds) {

		// 解放
		release();
		// 作成
		create();

		final int count = soundIds.length;

		for (int i = 0; i < count; i++) {

			final int id = mSoundPool.load(context, soundIds[i], 1);

			mSoundMap.put(soundIds[i], id);

		}
	}

	/**
	 * 解放
	 */
	public void release() {

		if (mSoundPool != null) {
			// 過去に読み込んだものをクリアする
			mSoundPool.release();
			// 解放
			mSoundPool = null;
		}
		// IDクリア
		mSoundMap.clear();

	}

	/**
	 * サウンドプール作成
	 */
	public void create() {
		// サウンドプール作成
		final int i = 10;
		mSoundPool = new SoundPool(i, AudioManager.STREAM_MUSIC, 0);
	}

	/**
	 * 再生
	 * 
	 * @param soundId
	 *            サウンドリソースID (R.raw.XXXXX)
	 */
	public void play(final int soundId) {

		if (mSoundMap == null) {
			return;
		}
		final Integer soundID = mSoundMap.get(soundId);
		if (soundID == null) {
			return;
		}
		final float leftVolume = 100;
		final float rightVolume = 100;
		final int priority = 1;
		final int loop = 0;
		final float rate = 1.2f;
		mSoundPool.play(soundID, leftVolume, rightVolume, priority, loop, rate);

	}

}
